package com.weiwei.easyapiinterface.controller;

import cn.hutool.json.JSONUtil;
import com.weiwei.easyapiclientsdk.model.AvatarParams;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * @ClassName AvatarController
 * @Description TODO
 * @Author lish
 * @Date 2023/5/9 0:37
 */
@RestController
@RequestMapping("/avatar")
@Slf4j
public class AvatarController {


    /**
     * 获取随机头像
     * @param avatarParams
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/avatarUrl")
    public String getAvatarUrlByPost(@RequestBody(required = false) AvatarParams avatarParams, HttpServletRequest request) throws Exception {
        //https://restapi.amap.com/v3/weather/weatherInfo?
        //这里使用https，因为使用http每次点击调用都是返回同一张头像，而不是重新获取，具体原因分析http和https的区别
        String avatarUrl = "https://www.loliapi.com/acg/pp/";
        //获取重定向后的URL
        String redirectUrl = getRedirectUrl(avatarUrl);
        log.info(redirectUrl);
        return redirectUrl;
    }


    /**
     * 获取重定向地址
     * @param path
     * @return
     * @throws Exception
     */
    private String getRedirectUrl(String path) throws Exception {
        //创建HTTP连接对象
        HttpURLConnection conn = (HttpURLConnection) new URL(path)
                .openConnection();
        //设置不跟随重定向,如果为true跟随重定向
        conn.setInstanceFollowRedirects(false);
        conn.setConnectTimeout(5000);
        String location = conn.getHeaderField("Location");
        return location;
    }
}
